package com.qingge.springboot.controller;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingge.springboot.entity.Signs;
import com.qingge.springboot.entity.User;
import com.qingge.springboot.service.ISignsService;
import com.qingge.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingge.springboot.common.Result;

import com.qingge.springboot.service.IExamService;
import com.qingge.springboot.entity.Exam;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 黎俊
 * @since 2022-06-14
 */
@RestController
@RequestMapping("/exam")
public class ExamController {

    @Resource
    private IExamService examService;
    @Resource
    private ISignsService signsService;

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Exam exam) {
        if(exam.getId() ==null){
   // exam.setTiem(DateUtil.now());
   // exam.setUserId(TokenUtils.getCurrentUser().getId());
        }

        examService.saveOrUpdate(exam);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        examService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        examService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(examService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(examService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String name) {
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");
                if (!"".equals(name)) {
            queryWrapper.like("username", name);
        }
//        if (!"".equals(email)) {
//            queryWrapper.like("email", email);
//        }
//        if (!"".equals(address)) {
//            queryWrapper.like("address", address);
//        }
        Page<Exam> page = examService.page(new Page<>(pageNum, pageSize), queryWrapper);
        for (Exam exam: page.getRecords()){
           setState(exam);
            examService.updateById(exam);
        }
        return Result.success(page);
    }

    @GetMapping("/page/front")
    public Result findPageFront(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name) {
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");
                if (!"".equals(name)) {
            queryWrapper.like("username", name);
        }
        Page<Exam> page = examService.page(new Page<>(pageNum, pageSize), queryWrapper);
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser.getRole().equals("ROLE_USER")){
            queryWrapper.eq("user",currentUser.getUsername());
        }
        //查出当前用户所以的考试
        List<Signs> signsList = signsService.list(new QueryWrapper<Signs>().eq("user_id", currentUser.getId()));
         for (Exam exam: page.getRecords()){
             exam.setEnable(false);
             Integer examId = exam.getId();
             //当且仅当当前用户报名列表中的考试是审核通过，我们才能设置，开始考试的按钮
             signsList.stream().filter(signs -> signs.getExamId().equals(examId)).findFirst().ifPresent(signs -> {
                 exam.setEnable("审核通过".equals(signs.getState()));
             });
       setState(exam);
       examService.updateById(exam);
         }
        return Result.success(page);
    }

    private void setState(Exam exam){
        String time = exam.getTime();
        DateTime dateTime = DateUtil.parse(time, "yyyy-MM-dd HH:mm");
        Date now = new Date();
        if (DateUtil.compare(dateTime,now) <=0 && DateUtil.compare(DateUtil.offsetMinute(dateTime,exam.getDuration()),now) >=0){
            exam.setState("进行中");
        } else if (DateUtil.compare(dateTime,now)>0) {
            exam.setState("未开始");
        }else {
            exam.setState("已结束");
        }
    }

}

